//初始化树结构（合并初始化）
var NodeSettingGroup;
if("undefined" == typeof setting2) {
	setting2 = '';
}
var setting3 = {
	data: {
		key: {
			name: "teamName"
		}
	}
};
NodeSettingGroup = $.extend({}, setting1, setting2, setting3);

var teamTree_ = new VanyBaseTree("treeDemo", "/base/team/load?token=" + sessionStorage.token, NodeSettingGroup);

setTimeout(function thisTree(){
	Jurisdiction();
	//判断是否展示操作区域按钮
	JurisdictionBefore("#treeTitle", "#rMenu");
	try {
		table_.teamCode =  $.fn.zTree.getZTreeObj("treeDemo").getSelectedNodes()[0].teamCode;
		table_.getData();
	} catch(e) {
		console.log(e)
	}
},100);

//标题中新增
var titleNode;
new Vue({
	el: "#treeTitle",
	methods: {
		titleOperation: function() {
			$("#titleOperation").css("visibility", "visible");
		},
		addTitle: function() {
			addNodes.resetForm("ruleForm");
			addNodes.treeAddVisible = true;
			//判断是否新增根节点
			titleNode = true;
		}
	}
});

//鼠标点击其他区域，弹框隐藏
$("body").bind("mousedown", function(event) {
	if(!(event.target.id == "titleOperation" || $(event.target).parents("#titleOperation").length > 0)) {
		$("#titleOperation").css("visibility", "hidden");
	}
});

// 树节点操作
new Vue({
	el: '#rMenu',
	methods: {
		// 删除节点
		del: function() {
			hideRMenu();
			var self = this;
			self.$confirm('是否删除当前群组?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(function() {
				VanyAjax("/base/team/delete", {
					teamCode: zTree.getSelectedNodes()[0].teamCode
				}).done(function(data) {
					var nodes = zTree.getSelectedNodes();
					if(nodes && nodes.length > 0) {
						zTree.removeNode(nodes[0]);
					}
					self.$message({
						type: 'success',
						message: '删除成功!'
					});
				}, true, this);
			}).catch(function() {
				self.$message({
					type: 'info',
					message: '已取消删除'
				});
			});
		},
		// 编辑节点
		Edit: function() {
			treeEdit.resetForm("ruleForm");
			hideRMenu();
			// 获取树节点相关信息
			var treeKey = zTree.getSelectedNodes()[0];
			for(var key in treeKey) {
				treeEdit.ruleForm[key] = treeKey[key];
				if(key == "state") {
					treeEdit.ruleForm[key] = zTree.getSelectedNodes()[0].state ==
						1 ? 1 : 0
				}
			}
			treeEdit.treeEditVisible = true;
		}
	}
});

//新增节点
var addNodes = new Vue({
	el: "#addRole",
	data: function() {
		return {
			treeAddVisible: false,
			labelPosition: 'right',
			ruleForm: {
				teamName: ''
			},
			rules: {
				teamName: {
					required: true,
					message: '请输入群组名称',
					trigger: 'blur'
				}
			}
		};
	},
	methods: {
		submitForm: function(formName) {
			var self = this;
			self.$refs[formName].validate(function(valid) {
				if(valid) {
					addNodes.treeAddVisible = false;
					VanyAjax("/base/team/add", {
						teamName: addNodes.ruleForm.teamName
					}).done(function(data) {
						var newNode = {
							teamName: addNodes.ruleForm.teamName
						};
						zTree.addNodes(null, newNode);
						addNodes.ruleForm.teamCode = '';
						addNodes.ruleForm.teamName = '';
					}, false, this);
				} else {
					console.log('error submit!!');
					return false;
				}
			});
		},
		resetForm: function(formName) {
			try{
				this.$refs[formName].resetFields();
			}catch(e){
				
			}
			this.ruleForm.teamCode = '';
			this.ruleForm.teamName = '';
		} //重置
	}
});

//树的修改
var treeEdit = new Vue({
	el: "#treeEdit",
	data: function() {
		return {
			treeEditVisible: false,
			labelPosition: 'right',
			ruleForm: {
				teamName: ''
			},
			rules: {
				teamName: {
					required: true,
					message: '请输入群组名称',
					trigger: 'blur'
				}
			}
		};
	},
	methods: {
		submitForm: function(formName) {
			var self = this;
			self.$refs[formName].validate(function(valid) {
				if(valid) {
					treeEdit.treeEditVisible = false;
					VanyAjax("/base/team/modify", {
						teamCode: zTree.getSelectedNodes()[0].teamCode,
						teamName: treeEdit.ruleForm.teamName
					}).done(function(data) {
						zTree.getSelectedNodes()[0].teamName = treeEdit.ruleForm.teamName; //获取名称
						zTree.refresh();
						self.$message({
							type: 'success',
							message: '已成功修改!'
						});
					}, false, this);
				} else {
					console.log('error submit!!');
					return false;
				}
			});
		},
		resetForm: function(formName) {
			try{
				this.$refs[formName].resetFields();
			}catch(e){
				
			}
		} //重置
	}
});

// //////////--------------表格-数据--------------------////////////
var table_ = new Vue({
	el: '#table',
	data: function() {
		return {
			tableData: [],
			total: 0,
			page: 1, // 默认显示第一页
			teamCode: "",
			pageSize: 100,
			pageIndex: 1,
			nodataFlag: false,
			listLoading: false, // 加载表格数据tableData
			editFormVisible: false, // 编辑界面是否显示
			editLoading: false,
			editFormRules: {
				name: [{
					required: true,
					message: '请输入姓名',
					trigger: 'blur'
				}]
			},
			// 编辑界面数据
			editForm: {
				id: 0,
				dingDanHao: '',
				jiaoYiJinE: '',
				jiaoYiShiJian: '',
				zhiFuFanShi: 0
			},
			// 列表选中列
			sels: [],
			tableHeight: "",
			searchValue: "",
			// 禁用、启用、全部
			stateCounts: [0, 0, 0],
			curFilter: "",
			curSelectedIndex: 0,
			// 给每一个行数据添加index_索引属性
			_index: 0,
			curTr: {}
		}
	},
	computed: {
		filtersStatusCount: function() {
			return [{
				text: "全部 (" + this.stateCounts[2] + ")",
				value: ""
			}, {
				text: "启用 (" + this.stateCounts[1] + ")",
				value: "1"
			}, {
				text: "禁用 (" + this.stateCounts[0] + ")",
				value: "0"
			}]
		},
		pages: function() {
			return Math.ceil(this.total / this.pageSize);
		}
	},
	mounted: function(value, oldvalue) {
		var self = this;
		this.$el.style.left = "210px";
		this.tableHeight = window.innerHeight - 215;
		var isScrollToBottom_ = function() {
			if(self.nodataFlag) {
				return false;
			}
			isScrollToBottom(this, self.getData);
		};
		this.$nextTick(function() {
			// 生成数据后，根据窗口默认table宽度展示
			// console.log("可视区域宽度111" + $("body").width());
			$(this.$el).stop(true, false).animate({
				width: $(".vany_authority").width() - 234
			});
			var tablebody_ = this.$children[1].$el;
			tablebody_ = tablebody_.getElementsByClassName("el-table__body-wrapper")[0];
			tablebody_.onscroll = function(e) {
				throttle(isScrollToBottom_, e);
			}
		});
	},
	methods: {
		// 获取表格数据 zTree.getSelectedNodes()[0].teamCode
		getData: function() {
			console.log(this.pageIndex);
			VanyAjax("/base/team/queryTeamer", {
				teamCode: zTree.getSelectedNodes()[0].teamCode,
				pageSize: this.pageSize,
				pageIndex: this.pageIndex,
				searchValue: this.searchValue
			}, "GET", ".el-table").done(function(data) {
				for(var i = 0; i < data.rows.length; i++) {
					if(data.rows[i].photoUrl == null) {
						data.rows[i].photoUrl = "/templates/img/default.jpg";
					}
				}
				if(data.total === 0) {
					this.nodataFlag = true;
					return;
				}
				if(this.pageIndex * this.pageSize >= data.total) {
					this.nodataFlag = true;
				}
				var rows = data.rows;
				for(var i = 0; i < rows.length; i++) {
					/* 坑，索引赋值无法触发更新 */
					this.stateCounts[parseInt(rows[i]["status"])]++;
					rows[i]._index = this._index;
					this.tableData.push(rows[i]);
					this._index++;
				}
				this.pageIndex++;
				this.hasResetPagination = false;
				VanyAjax.prototype.hideLoading();
			}, false, this);
		},
		updateIndex: function() {
			this._index = this.tableData.length;
			for(var i = 0; i < this._index; i++) {
				this.tableData[i]._index = i;
			}
		},
		getIndexById: function(id) {
			for(var i = 0; i < this.tableData.length; i++) {
				if(id === this.tableData[i].userId) {
					return i;
				}
			}
			return false;
		},
		filterStatus: function(command) {
			if(command === "1") {
				if(this.curFilter.indexOf("启用") > -1) {
					return;
				}
				this.curFilter = "启用(" + this.stateCounts[1] + ")";
			} else if(command === "0") {
				if(this.curFilter.indexOf("禁用") > -1) {
					return;
				}
				this.curFilter = "禁用(" + this.stateCounts[0] + ")";
			} else {
				if(this.curFilter.indexOf("全部") > -1) {
					return;
				}
				this.curFilter = "全部(" + this.stateCounts[2] + ")";
			}
			this.status = command;
			this.searchTable();
		},
		resetPaginationParams: function() {
			this.tableData = [];
			this.tableData_ = [];
			this.pageIndex = 1;
			this.nodataFlag = false;
			this._index = 0;
		},
		// 表格操作区域下拉选择
		tableSelect: function(command) {
			$("#handleCommand").html(command);
		},
		// 人员筛选器
		openPersonFilter: function() {
			if(!zTree.getSelectedNodes()){
				this.$alert('请选择要添加到的群组！', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
					customClass: "notLoadingThis"
				});
				return;
			}
			var self = this;
			if(!this.personFilter) {
				this.personFilter = VanyFilter({
					mountEl: "#content",
					title: "选择人员",
					tabs: [{
						"name": "人员",
						"id": "renyuan",
						"filterUrl": "/base/userCondition/getCondition",
						"url": "/base/userCondition/getBaseUserInfo",
						"pagination": true,
						"isPersonSeleted": true,
						"defaultProps": {
							"children": 'children',
							"label": 'userName',
							"id": "userId"
						}
					}],
					ok: function() {
						VanyAjax("/base/team/addTeamUsers", {
							teamCode: zTree.getSelectedNodes()[0].teamCode,
							userIds: this.tabs[0].allNodesId.join(",")
						}, "POST", ".vanymodal_vueversion").done(function(data) {
							table_.resetPaginationParams();
							table_.getData();
							VanyAjax.prototype.hideLoading()
							this.personFilter.hide();
						}, true, self);
						//table_.getData();
						return false;
					}
				});
			} else {
				this.personFilter.clear();
				this.personFilter.show();
			}
		},
		// 表格操作区域批量导出
		Batchexport: function() {
			var self = this;
			if(this.tableData.length === 0) {
				this.$alert("没有数据。", "提示", {
					type: 'warning',
					customClass: "notLoadingThis"
				});
				return false;
			}
			self.$confirm('确认导出?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				customClass: "notLoadingThis"
			}).then(function() {
				location.href = "/base/user/export?token=" + sessionStorage.token + "&type=TEAM&teamCode=" + zTree.getSelectedNodes()[0].teamCode;
			}).catch(function() {})
		},
		gender: function(row, column) {
			return row.Gender == 1 ? '男' : '女';
		},
		handleCurrentChange: function(val) {
			this.page = val;
		},
		// 選中复选框
		selsChange: function(sels) {
			this.sels = sels;
			multiSelectPerson.multiSelectPersonVisible = this.sels.length !== 0 ? true : false
		},
		restoreTableData: function(val) {
			if(val.length === 0) {
				// 还原
				this.searchTable();
			}
		},
		/**
		 * 按搜素关键字过滤表格数据
		 */
		searchTable: function(val) {
			this.resetPaginationParams();
			this.getData();
		},
		/**
		 * 表格数据过滤器 
		 * 过滤对象: Obj item 
		 * return Bool
		 */
		createFilter: function(item, state) {
			for(var key in item) {
				if(item[key].toString().indexOf(this.keyWord) > -1) {
					return true
				}
			}
			return false;
		},
		/**
		 * 点击行时显示个人资料卡片
		 */
		showPersonCard: function(row, event, column) {
			if(column.type === "selection" || this.sels.length > 0) {
				return;
			}
			this.curSelectedIndex = this.getIndexById(row.userId);
			this.curTr = row;
			// 坑！后端有些字段没值是不返回该字段的，所以先要重置所有再赋值
			// 不从缓存里拉人员信息了
			/*
			 * for(var key in personCard.personinfo) {
			 * personCard.personinfo[key] = ""; } for(var key in row) {
			 * personCard.personinfo[key] = row[key]; }
			 */
			//personCard.getData(row.userCode);
		},
		filterTag: function(value, row) {
			return row.State == value;
		},
	}
});

// 人员多选操作
var multiSelectPerson = new Vue({
	el: "#multiSelectPerson",
	data: {
		multiSelectPersonVisible: false,
		isIE: !!window.VBArray
	},
	computed: {
		seletedPersons: function() {
			return table_.sels;
		},
		title: function() {
			return "批量选择(" + table_.sels.length + ")";
		}
	},
	updated: function() {
		// 全选人员滚动条
		var dialogBody = this.$el.getElementsByClassName("el-dialog__body")[0];
		// 47是header高度，62是footer高度，
		dialogBody.style.maxHeight = window.innerHeight - 47 - 62 + "px";
		dialogBody.style.overflowY = "auto";
		Jurisdiction();
	},
	methods: {
		/**
		 * 删除所选人员
		 */
		deleteSeletedPerson: function() {
			var userIdList = this.seletedPersons.map(function(item) {
				return item.userTeamId;
			}).join(",");
			var self = this;
			this.$confirm('确认删除该所选用户？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(function() {
				VanyAjax("/base/team/delTeamUsesr", {
					teamUserIds: userIdList
				}).done(function(data) {
					this.remove();
					table_.updateIndex();
					VanyAjax.prototype.hideLoading();
				}, true, self);
			}).catch(function() {})
		},
		remove: function() {
			var sels = [].concat(table_.sels);
			sels = this.quickSort(sels, "_index");
			for(var i = 0; i < sels.length; i++) {
				table_.tableData.splice(sels[i]._index, 1);
				for(var j = i + 1; j < sels.length; j++) {
					sels[j]._index--;
				}
			}
			table_.sels = [];
		},
		/**
		 * 从所选择人员中移除 
		 * 移除类别: Number rowindex 
		 * rowindex如果不传则表示移除所有，默认只移除指定项
		 */
		removeFromSeleted: function(rowindex) {
			// 使用splice而不是table_.$refs["table"].clearSelection(table_.sels[rowindex])
			// 是因为会导致循环的数据引用，清空一个会清空所有
			rowindex !== undefined ? table_.sels.splice(rowindex, 1) : table_.$refs["table"].clearSelection()
			// sels为空时应该关闭弹框
			if(table_.sels.length === 0) {
				multiSelectPerson.multiSelectPersonVisible = false;
			}
		},
		quickSort: function(arr, _key) {
			if(arr.length <= 1) {
				return arr;
			}
			var pivotIndex = Math.floor(arr.length / 2),
				pivot = arr.splice(pivotIndex, 1)[0],
				left = [],
				right = [];
			if(_key) {
				for(var i = 0; i < arr.length; i++) {
					if(arr[i][_key] < pivot[_key]) {
						left.push(arr[i]);
					} else {
						right.push(arr[i]);
					}
				}
				return this.quickSort(left, _key).concat([pivot], this.quickSort(right, _key));
			} else {
				for(var i = 0; i < arr.length; i++) {
					if(arr[i] < pivot) {
						left.push(arr[i]);
					} else {
						right.push(arr[i]);
					}
				}
				return this.quickSort(left, _key).concat([pivot], this.quickSort(right, _key));
			}
		}
	}
});

/**
 * 函数节流器，在时间间隔内不触发函数（优化） 
 * 应用场景：需要反复重复执行的事件，如快速重复点击按钮等等 
 * method: 函数 function a(){}
 * throttle(a)
 */
function throttle(method, context) {
	clearTimeout(method.tId);
	method.tId = setTimeout(function() {
		method.call(context);
	}, 100);
}

/**
 * 判断一个可滚动元素是否滚动到了底部 
 * e: 元素 
 * fn: 滚动到底部需要执行的回调 
 * isScrollToBottom(div, function(){})
 */
function isScrollToBottom(e, fn) {
	// e.srcElement存在兼容性问题，并非标准特性
	// https://developer.mozilla.org/zh-CN/docs/Web/API/Event/target
	// 支持 IE6-8
	var target_ = e.target || e.srcElement,
		// 距离顶部高度
		scrollTop = target_.scrollTop,
		// 滚动区域高度
		scrollHeight = target_.scrollHeight,
		// 文档元素高度
		clientHeight = target_.clientHeight;
	// 文档坐标和视口坐标转换，判断元素滚动到了底部
	if(scrollTop + clientHeight == scrollHeight) {
		if(fn) {
			fn.call();
		}
	}
}

/**
 * 将源对象合并到目标对象中去——内部方法 
 * src: 源对象 
 * to: 目标对象 
 * return 目标对象 
 * a = {"a": "a"} 
 * b = {"b": "b"} 
 * extend_(b, a) → {a: "a", b: "b"}
 */
function extend_(srcObj, toObj) {
	for(var key in toObj) {
		srcObj[key] = toObj[key];
		return srcObj;
	}
}

/**
 * 判断是否为字符串 
 * o: 对象 
 * isString_("string") → true 
 * isString_([]) → false
 */
function isString_(o) {
	return Object.prototype.toString.call(o) === "[object String]";
}